<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :footer="null"
    :maskClosable="false"
    switchFullscreen
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">

    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beLaidUpTime">
              <j-date placeholder="请选择入库日期" v-model="model.beLaidUpTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryId">
              <a-select
                show-search
                placeholder="请选择仓库"
                option-filter-prop="children"
                v-model="model.depositoryId"
                style="width: 100%"
                :filter-option="filterOptionDepository">
                <a-select-option :value="item.id" v-for="(item,index) in depositoryData" :key="index">
                  {{ item.depositoryName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" v-if="model.relevanceCheckNo != null && model.relevanceCheckNo != '' ">
            <a-form-model-item label="关联盘点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relevanceCheckNo">
              <a-input v-model="model.relevanceCheckNo" disabled=""/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="{ xs: {span: 24}, sm: {span: 2}}" :wrapperCol="{ xs: {span: 24},sm: {span: 16} }">
              <a-textarea v-model="model.remark" :rows="3" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="操作" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-button type="primary" :loading="loading" style="margin-right: 10px" @click="submitSave(2)">提交审批</a-button>
              <a-button type="primary" @click="submitSave(1)">保存草稿</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>

    <div>
      <a-button class="editable-add-btn" @click="handleAdd" style="margin-bottom: 10px" >
        添加材料
      </a-button>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        class="j-table-force-nowrap"
        bordered
        :data-source="materialData"
        :columns="columns"
        :pagination="false"
        :rowKey="(record,index)=>{return index}"
        >
        <a slot="materialName" @click="showMaterialStock(record)" slot-scope="text,record">{{ text }}</a>

        <template v-for="col in ['materialNum', 'unitPrice','remark','subtotal']" :slot="col" slot-scope="text, record, index">
          <div :key="col" v-if="col !== 'subtotal'">
            <a-input
              :id="col"
              style="margin: -5px 0;width: 90px;text-align: center"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
          </div>
          <div :key="col" v-if="col === 'subtotal'">
            <span>{{text}}</span>
          </div>
        </template>

        <template slot="operation" slot-scope="text, record, index">
          <a-popconfirm title="确定删除这条记录吗" @confirm="() => onDelete(record.key)">
            <a>删除</a>
          </a-popconfirm>
        </template>

      </a-table>
    </div>

    <select-material-modal ref="SelectMaterialModal" @ok="chooseMaterialOk($event)"></select-material-modal>
    <material-stock-modal ref="materialStockModal"></material-stock-modal>
  </j-modal>
</template>

<script>
  import {httpAction, getAction,deleteAction} from '@/api/manage'
  import '@/assets/less/TableExpand.less'
  import selectMaterialModal from "../../purchaseOrder/modules/selectMaterialModal";
  import materialStockModal from "../../purchaseOrder/modules/materialStockModal";

  export default {
    name: 'purchaseOrderModal',
    components: {
      selectMaterialModal,
      materialStockModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },

    data() {
      return {
        loading: false,
        depositoryData: [],
        materialData:[],
        cacheData: [],
        editingKey: '',
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: '3%',
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '名称',
            dataIndex: 'materialName',
            width: '13%',
            align: "center",
            slots: { title: 'customTitle' },
            scopedSlots: { customRender: 'materialName' },
          },
          {
            title: '型号',
            dataIndex: 'modelNumber',
            width: '12%',
            align: "center",
            scopedSlots: {customRender: 'modelNumber'},
          },
          {
            title: '规格',
            dataIndex: 'specifications',
            width: '13%',
            align: "center",
            scopedSlots: {customRender: 'specifications'},
          },
          {
            title: '品牌',
            dataIndex: 'brand',
            width: '12%',
            align: "center",
            scopedSlots: {customRender: 'brand'},
          },
          {
            title: '单位',
            dataIndex: 'unit',
            width: '5%',
            align: "center",
          },
          {
            title: '市场价',
            dataIndex: 'marketPrice',
            width: '5%',
            align: "center",
            scopedSlots: {customRender: 'marketPrice'},
          },
          {
            title: '预算价',
            dataIndex: 'estimatedCost',
            width: '5%',
            align: "center",
            scopedSlots: {customRender: 'estimatedCost'},
          },
          {
            title: '成本价',
            dataIndex: 'costPrice',
            width: '5%',
            align: "center",
          },
          {
            title: '单价',
            dataIndex: 'unitPrice',
            width: '8%',
            align: "center",
            scopedSlots: {customRender: 'unitPrice'},
          },
          {
            title: '数量',
            dataIndex: 'materialNum',
            width: '8%',
            align: "center",
            scopedSlots: {customRender: 'materialNum'},
          },
          {
            title: '金额',
            dataIndex: 'subtotal',
            width: '5%',
            align: "center",
            scopedSlots: {customRender: 'subtotal'},
          },
          {
            title: '备注',
            dataIndex: 'remark',
            width: '8%',
            align: "center",
            scopedSlots: {customRender: 'remark'},
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '10%',
            align: "center",
            scopedSlots: {customRender: 'operation'},
          },
        ],
        title: '',
        width: '90%',
        visible: false,
        disableSubmit: false,
        fullscreen: true,
        keyIndex: 0,
        addRowBeginIndex: 0,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {
          beLaidUpTime: [{ required: true, message: '请选择入库日期' }],
          depositoryId: [{ required: true, message: '请选择仓库' }],
          remark: [
            { required: true, message: '备注不能为空' },
            { max: 100, message: '最多输入100个字符' },
          ],
        },
        selectedRowKeys: [],
        selectedRows: [],
        url: {
          add: "/ghSupplychainOtherInDepositoryOrder/add",
          edit: "/ghSupplychainOtherInDepositoryOrder/edit",
          queryById: "/ghSupplychainOtherInDepositoryOrder/queryById",
          queryDepositoryList: "/ghSupplychainDepository/allList",
          queryOtherInDepositoryOrderItemList: "/ghSupplychainOtherInDepositoryOrderItem/list",
          deleteOtherInDepositoryOrderItem: "/ghSupplychainOtherInDepositoryOrderItem/delete",
        }
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    created() {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      //查询库存并显示
      showMaterialStock(record){
        this.$refs.materialStockModal.title = "库存详情";
        this.$refs.materialStockModal.showMaterialStock(record);
      },
      //加载仓库
      loadDepositoryData(){
        getAction(this.url.queryDepositoryList).then((res) => {
          if (res.success) {
            this.depositoryData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      filterOptionDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },

      handleChange(value, key, column) {
        const newData = [...this.materialData];
        const target = newData.find(item => key === item.key);
        if (target) {
          target[column] = value;
          if (target.unitPrice != null && target.materialNum != null){
            target['subtotal'] = (target.unitPrice * target.materialNum).toFixed(2);
          }
          this.materialData = newData;
        }
      },
      onDelete(key) {
        if(this.model.id){
          if (key <= this.addRowBeginIndex){
            let obj=this.materialData.find(function (obj) {
              return obj.key === key;
            })
            deleteAction(this.url.deleteOtherInDepositoryOrderItem,{id:obj.id}).then(res=>{
              if (res.success){
                this.$message.success(res.message)
              }else {
                this.$message.warning(res.message)
              }
            })
          }
        }
        const data = [...this.materialData];
        this.materialData = data.filter(item => item.key !== key);
      },
      handleAdd() {
        this.$refs.SelectMaterialModal.title = "请选择材料";
        this.$refs.SelectMaterialModal.add();
      },

      chooseMaterialOk(arr){
        //去重
        let newArr = Array.from(new Set(arr));
        for (let i=0;i<newArr.length;i++){
          newArr[i].key = this.keyIndex;
          newArr[i].materialId = newArr[i].id;
          newArr[i].id = null;
          newArr[i].unitPrice = newArr[i].costPrice;
          this.materialData.push(newArr[i]);
          this.cacheData.push(newArr[i]);
          this.keyIndex++;
        }
        //todo
      },

      addOtherInDepositoryOrder() {
        this.visible = true;
      },
      editOtherInDepositoryOrder(record) {
        this.model = Object.assign({}, record);
        getAction(this.url.queryOtherInDepositoryOrderItemList, {id:record.id}).then((res) => {
          if (res.success) {
            this.materialData = res.result.records||res.result;
            for (let i=0;i<this.materialData.length;i++){
              this.materialData[i].key = i.toString();
              this.cacheData.push(this.materialData[i]);
            }
            this.keyIndex = this.materialData.length;
            this.addRowBeginIndex = this.materialData[this.materialData.length-1].key;
          }else{
            this.$message.warning(res.message)
          }
        })
        this.visible = true;
      },
      //提交审批，保存草稿
      submitSave(status){
        this.loading = true;
        const that = this;
        let httpurl = '';
        let method = '';
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.materialData.length === 0){
              this.$message.warning("请至少添加一条有效数据")
              this.loading = false;
              return;
            } else {
              if (!this.model.id) {
                httpurl += this.url.add;
                method = 'post';
              } else {
                httpurl += this.url.edit;
                method = 'put';
              }
            }
            let total = 0;
            for (let i=0;i<this.materialData.length;i++){
              if (this.materialData[i].materialNum == null || this.materialData[i].materialNum == 0){
                this.$message.warning("请输入【"+this.materialData[i].materialName+"】材料的数量")
                return;
              } else {
                if (this.materialData[i].materialNum < 0){
                  this.$message.warning("【"+this.materialData[i].materialName+"】材料的数量输入有误")
                  return;
                }
              }

              if (this.materialData[i].unitPrice == null || this.materialData[i].unitPrice == 0){
                this.$message.warning("请输入【"+this.materialData[i].materialName+"】材料的单价")
                return;
              } else {
                if (this.materialData[i].unitPrice < 0){
                  this.$message.warning("【"+this.materialData[i].materialName+"】材料的单价输入有误")
                  return;
                }
              }
              total += this.materialData[i].unitPrice * this.materialData[i].materialNum;
            }
            this.model.materialOtherOrderItemVos = this.materialData;
            this.model.price = total;
            this.model.orderStatus = status;
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              this.loading = false;
              that.close();
            })
          } else {
            this.loading = false;
          }
        })
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectionRows
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.onClearSelected();
        this.materialData = [];
        this.cacheData = [];
        this.model = {};
        this.keyIndex = 0;
        this.editingKey = '';
      },
      handleCancel() {
        this.close()
      },

    }
  }
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  .tableHiddle {
    display: none;
  }
</style>